/*
 * DelimFramer.c
 *
 *  Created on: 2012. 5. 8.
 *      Author: yjpark
 */

#include <stdio.h>
#include <stdbool.h>
#include <stdint.h>
#include <string.h>
#include "Protocol.h"


// frame delimiter
static const char DELIMITER = '\0';

// complete
int Delim_PutMsg(CalcInfo *ci, uint8_t *outBuf, size_t bufSize, size_t hSize, FILE *channel) {

	// message size
	int mSize = 0;

	// framming 전에 마지막 field delimiter 는 제거하고, '\0'로 대체
	memset(strrchr(outBuf, '|'), '\0', 1);

	// framming 전에 종료 문자 '\n' 없으면 추가
	if(strchr(outBuf, '\n') == NULL) {
		memset(strchr(outBuf, '\0'), '\n', 1);
	}

	// move for header
	memmove(outBuf+hSize, outBuf, bufSize-hSize);

	// header into outBuf
	// binary encode
	memcpy(outBuf, ci, hSize);

	// '\0' framming delimiter 추가
	memset(outBuf+bufSize+sizeof(DELIMITER), DELIMITER, sizeof(DELIMITER));

	// header+data into channel
	if((mSize = fwrite(outBuf, sizeof(uint8_t), bufSize+sizeof(DELIMITER), channel)) < 0)
		return -1;

	// send message
	fflush(channel);

	return mSize;
}

// complete
int Delim_GetNextMsg(uint8_t *inBuf, size_t bufSize, FILE *channel) {
	int count = 0;
	int nextChar;
	while (count < bufSize) {
		nextChar = getc(channel);

		// End of stream
		if (nextChar == DELIMITER)
			break;

		inBuf[count++] = nextChar;
	}

	return count;
}
